package com.devshephard.thread;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CountDownLatch;


@Component
@Configuration
public class testMultiThread {
    public static void main(String[] args) {
        List<String> listParent = new ArrayList<>();

        //测试每100条数据插入开一个线程

        for (int i = 0; i < 10000; i++) {
            listParent.add(String.valueOf(i));
        }

        List<List<String>> logOutputResults = groupList(listParent);

        CountDownLatch countDownLatch = new CountDownLatch(logOutputResults.size());

        ApplicationContext applicationContext = new AnnotationConfigApplicationContext();
        AsyncService asyncService = (AsyncService) applicationContext.getBean("AsyncService");

        for (List<String> listSub:logOutputResults) {
            asyncService.executeAsync(listSub,countDownLatch);
        }
        try {
            countDownLatch.await(); //保证之前的所有的线程都执行完成，才会走下面的；
            // 这样就可以在下面拿到所有线程执行完的集合结果
        } catch (Exception e) {
            System.out.println("阻塞异常:"+e.getMessage());
        }
        System.out.println("FINISHHHHHHHHHHHHHHHHH");
    }

    public static List<List<String>> groupList(List<String> list) {
        List<List<String>> listGroup = new ArrayList<List<String>>();
        int listSize = list.size();
        //子集合的长度，比如 500
        int toIndex = 100;
        for (int i = 0; i < list.size(); i += 100) {
            if (i + 100 > listSize) {
                toIndex = listSize - i;
            }
            List<String> newList = list.subList(i, i + toIndex);
            listGroup.add(newList);
        }
        return listGroup;
    }

}
